package com.cn.wolf.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 自定义handler需要继承netty规定好的HandlerAdapter
 *
 * @author huangy
 * @since 2023/1/27 10:34 上午
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) {
        System.out.println("server context: " + context);
        //处理接收客户端发送过来的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到来自客户端的信息: " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端信息: " + context.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext context) throws Exception {
        //发送消息给客户端
        context.writeAndFlush(Unpooled.copiedBuffer("你好客户端~", CharsetUtil.UTF_8));
    }

    //异常处理 关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
